package com.hqq.exercise.list.util;

import com.hqq.exercise.list.ListNode;

/**
 * ListUtil 链表工具类
 * Created by heqianqian on 2017/8/24.
 */
public class ListUtil {

    /**
     * 根据数组创建单链表
     */
    public static ListNode build(int[] array) {
        return buildList(array, 0);
    }

    private static ListNode buildList(int[] array, int index) {
        if (index == array.length - 1) {
            return new ListNode(array[array.length - 1]);
        }
        ListNode head = new ListNode(array[index]);
        head.next = buildList(array, ++index);
        return head;
    }

    /**
     * 打印链表
     */
    public static void print(ListNode head) {
        while (head != null) {
            System.out.print(head.data + " ");
            head = head.next;
        }
    }

    /**
     * 链表转ArrayList
     */
    public static int[] list2Array(ListNode head) {
        //TODO 待优化
        int[] result = new int[length(head)];
        int index = 0;
        while (head != null) {
            result[index++] = head.data;
            head = head.next;
        }
        return result;
    }

    /**
     * 计算链表长度
     */
    public static int length(ListNode head) {
        ListNode temp = head;
        int length = 0;
        while (temp != null) {
            length++;
            temp = temp.next;
        }
        return length;
    }
}
